<template>
  <div class="page">
    <div class="page-content ptr-content">
      <div class="ptr-preloader">
        <div class="preloader"></div>
        <div class="ptr-arrow"></div>
      </div>
      <div style="height:95%" class="list-block">
        <f7-list media-list style="margin-top:5px;">
          <f7-list-item
            chevron-center
            link="#"
            v-for="(problem, i) in problems"
            :key="problem.checkQualityProblemId"
            :title="problemTitle(problem)"
            :subtitle="problemSubtitle(problem)"
            :text="problemText(problem)"
            :badge="problem.status"
            :badge-color="problemBadgeColor(problem)"
            @click="submitedProblemClick(problem)"
          >
            <img slot="media" width="80" height="80" :src="problemImage(problem)" />
          </f7-list-item>
        </f7-list>
      </div>
    </div>
  </div>
</template>

<script>
	import eventBus from '@/utils/eventBus.js';
	import store from '@/store';
	import Common from '@/utils/Common.js';
	import DateUtil from '@/utils/DateUtil.js';
	import db from '@/utils/db';
	import {
		getUser,
		setUser,
		clearUser
	} from '@/utils/auth';
	export default {
		name: "ProblemList",
		store: store,
		props: {
			problems: {
				type: Array,
				default: function() {
					return [];
				}
			},
			task: ""
		},
		methods: {
			problemTitle: function(problem) {
				var title = '';
				if (problem.problemClassId != null) {
					var problemClass = this.$store.state.global.problemClassMap[problem.problemClassId];
					title = problemClass.problem_class_name;
					var parentProblemClassId = problemClass.parent_problem_class_id;
					if (parentProblemClassId != null) {
						title =
							this.$store.state.global.problemClassMap[parentProblemClassId].problem_class_name +
							' - ' + title;
					}
				}
				return title;
			},
			problemSubtitle: function(problem) {
				var subtitle = '';
				if (problem.problemId != null) {
					subtitle = this.$store.state.global.problemMap[problem.problemId].problem_name;
				}
				return subtitle;
			},
			problemText: function(problem) {
				var text = '';
				if (problem.registDate != null) {
					text += DateUtil.dateToStr('yyyy-MM-dd HH:mm', problem.registDate) + ' ';
				}
				if (problem.place != null) {
					text += problem.place;
				}
				return text;
			},
			problemImage: function(problem) {
				if (problem.imageFile && problem.imageFile.length > 0) {
					if (problem.smallImageFile && problem.smallImageFile.length > 0) {
						return problem.smallImageFile[0].url;
					} else {
						return problem.imageFile[0].url + "?x-oss-process=image/resize,m_fixed,h_80,w_80";
					}
				} else {
					return '';
				}
			},
			problemBadgeColor: function(problem) {
				switch (problem.status) {
					case '已通过':
						return 'green';
					case '待整改':
						return 'red';
					case '待复验':
						return 'orange';
					case '检查完毕':
						return 'green';
					case '已整改':
						return 'blue';
					case '已关闭':
						return ''
				}
				return '';
			},
			submitedProblemClick: function(problem) {
				var self = this;
				var url = "";
				if (this.task === "local") {
					url = "/LocaleCheck";
					switch (problem.status) {
						case '已通过':
							url += 'Complete';
							break;
						case '待整改':
							url += 'Repair';
							break;
						case '待复验':
							url += 'Reinspect';
							break;
						case '已关闭':
							url += 'Close';
							break;
					}
				} else {
					url += "/QualityMeasureProblem";
					switch (problem.status) {
						case '检查完毕':
							url += 'Complete?qualityMeasureProblemId=';
							url += problem.qualityMeasureCheckqualityProblemId;
							//url += "Complete";
							break;
						case '待整改':
							url += 'Repair';
							break;
						case '已整改':
							url += 'Reinspect';
							break;
					}
				}
				var router = this.$f7router.navigate(url, {
					props: {
						checkQualityProblem: problem,
						module: 'unprocess',
						sourceIsUnprocessed: true
					}
				});
				router.off('deleteProblemReinspect');
				router.on('deleteProblemReinspect', function(problem) {
					db.remove("offline_local_check_reinspect", problem);
				});
				router.off('deleteProblemSendBack');
				router.on('deleteProblemSendBack', function(problem) {
					db.remove("offline_local_check_sendBack", problem);
				}); 
				router.off('deleteProblemRepair');
				router.on('deleteProblemRepair', function(problemTid) {
					db.remove("offline_local_check_repair", problemTid);
				});
				router.off('deleteProblemSendBack');
				router.on('deleteProblemSendBack', function(tid) {
					db.remove("offline_local_check_sendBack", tid);
				}); 
				router.off('problemStautsChange');
				router.on('problemStautsChange', function(checkProblem) {
					if(self.task === "local") {
						self.updateOrInsert('tmp_unprocessed_problem_local_check_unprocessed', self.objToArr(checkProblem),
							checkProblem.id);
						self.updateOrInsert('tb_checkquality_problem', self.objToArr(checkProblem),
						checkProblem.id);
					}else{
						self.updateOrInsert('tmp_unprocessed_problem_quality_measure_unprocessed', self.objToArr(checkProblem),
							checkProblem.id);
					}
				});
				router.off('problemChangeRepair');
				router.on('problemChangeRepair', function(element) {
					self.problemChangeRepair(element);
				});
			},
			objToArr: function(obj){// 对象转换数组 
				var arr = [];
				if(obj instanceof Object) {
					arr.push(obj);
				}else{
					arr = obj;
				}
				return arr;
			},
			updateOrInsert: function(tableName, element, idValue) {
				var self = this;
				let sql = "select count(*) from " + tableName + " where id = \"" + idValue +"\"";
				Common.executeSql(sql, [])
				.then(result => {
					if (result.rs.rows.length > 0) {
						db.update(tableName, element);
					} else {
						db.insert(tableName, element);
					}
					eventBus.$emit("load-local-list");
				}).catch(error => {
					console.error(error);
					return Promise.resolve();
				});
			},
			problemChangeRepair: function(element) {
				let self = this;
				var currentUser = getUser();
				var localCheckProblemRepairs = element.repairList;
				var localCheckProblem = element.problem;
				var sql = "select id, update_time " +
							"from tb_checkquality_repair t ";
				var localMap = {};	
				let remoteMap = {};
				Common.executeSql(sql, [])
				.then(result => {
					for(var i = 0; i < result.rs.rows.length; i++) {
						var row = result.rs.rows.item(i);
						var item = {};
						item.id = row['id'];
						item.update_time = row['update_time'];
						localMap[item.id] = item;
					}
					var elements = [];
					for(var i = 0; i < localCheckProblemRepairs.length; i++) {
						var localCheckProblemRepair = localCheckProblemRepairs[i];
						if(localMap[localCheckProblemRepair.id] == null) {
							elements.push(localCheckProblemRepair);
						}else if(localMap[localCheckProblemRepair.id].update_time != localCheckProblemRepair.updateTime) {
							remoteMap[localCheckProblemRepair.id] = localCheckProblemRepair;
						}
					}
					return db.insert("tb_checkquality_repair", elements);
				}).then(() => {
					let elements = [];
					for(let remoteId in remoteMap) {
						elements.push(remoteMap[remoteId]);
					}
					return db.update("tb_checkquality_repair", elements);
				}).then(result => {
					self.updateOrInsert('tmp_unprocessed_problem_local_check_unprocessed', self.objToArr(localCheckProblem),
							localCheckProblem.id);
					self.updateOrInsert('tb_checkquality_problem', self.objToArr(localCheckProblem),
					localCheckProblem.id);
				}).catch(error => {
					console.error(error);
					return Promise.resolve();
				});
			}
		},
		mounted: function() {
			/* var self = this;
			var ptrContentProcessed = this.Dom7('.ptr-content');
			ptrContentProcessed.on('ptr:refresh', function(e) {
				e.detail();
				eventBus.$emit("change-date", false);
			}); */
		}
	}
</script>

<style scoped>
</style>
